<template>
  <u-upload
    :fileList="fileList1"
    @afterRead="afterRead"
    @delete="deletePic"
    name="1"
    multiple
    :maxCount="maxCount"
    :accept="accept"
  ></u-upload>
</template>

<script>
	import {
		baseUrl
	} from '@/api/base.js'; //导入接口的前缀地址
  export default {
    props: {
      accept: {
        type: String,
        default: 'image'
      },
      maxCount: {
        type: Number,
        default: 9
      },
      uploadUrl: {
        type: String,
        default: '/api/upload/uploadFile'
      },
      inputName: {
        type: String,
        default: 'file'
      },
      modelValue: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        fileList1: [],
      };
    },
    watch: {
      modelValue: {
        handler(val) {
          this.fileList1 = val || []
        },
        immediate: true
      },
      fileList1: {
        handler(val) {
          this.$emit('update:modelValue', val)
        },
        deep: true
      }
    },
    methods: {
      // 删除图片
      deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1);
        this.$emit('delete', event.index);
        this.$emit('update:modelValue', this.fileList1.slice());
      },
      // 新增图片
      async afterRead(event) {
        // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
        let lists = [].concat(event.file);
        let fileListLen = this[`fileList${event.name}`].length;
        lists.map((item) => {
          this[`fileList${event.name}`].push({
            ...item,
            status: "uploading",
            message: "上传中",
          });
        });
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url);
          let item = this[`fileList${event.name}`][fileListLen];
          this[`fileList${event.name}`].splice(
            fileListLen,
            1,
            Object.assign(item, {
              status: "success",
              message: "",
              url: result,
            })
          );
          fileListLen++;
        }
		console.log(this.fileList1,'0000')
        this.$emit('success', this.fileList1);
        this.$emit('update:modelValue', this.fileList1.slice());
      },
      uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: baseUrl+"/api/upload/uploadFile",
            filePath: url,
            name: "file",
            formData: {
              user: "test",
            },
            success: (res) => {
              let data = res.data ? JSON.parse(res.data) : {};
              if (data.code == 200) {
                // 处理返回的URL，确保不会出现重复的文件名
                let fileUrl = data.data;
                if (fileUrl.includes('20250512')) {
                  fileUrl = fileUrl.replace('20250512/', '');
                }
                resolve(fileUrl);
              } else {
                uni.showToast({
                  title: data.msg || '上传失败',
                  icon: 'none'
                });
                reject(data);
              }
            },
            fail: (err) => {
              uni.showToast({
                title: '上传失败',
                icon: 'none'
              });
              reject(err);
            }
          });
        });
      },
    },
  };
</script>
